Ext.define('truckplanner.controller.Missions', {
    
	extend: 'Ext.app.Controller',   
    	
    stores : ['Missions'],
    
    models : ['Mission'],
    
    views: ['mission.Main','mission.List','mission.Calendar','mission.Edit'],
    
	refs: [
           {ref: 'missionList', selector: 'missionlist'},
           {ref: 'missionEditor', selector: 'missioneditor'},
           {ref: 'missionEditorNew', selector: 'missioneditor button[action=new]'},
           {ref: 'missionEditorSave', selector: 'missioneditor button[action=save]'},
           {ref: 'missionEditorCancel', selector: 'missioneditor button[action=cancel]'},
           {ref: 'missionCalendar', selector: 'missioncalendar'}
    ],
    
    init: function() {
    	this.control({
            'missionlist': {
            	cellclick : this.mayDelete,
            	selectionchange: this.editSelectedMission
            },
            'missioneditor button[action=new]': {
            	click: this.newMission
            },
            'missioneditor button[action=save]': {
            	click: this.saveMission
            },
            'missioneditor button[action=cancel]': {
            	click: this.cancelMission
            },
            'missioncalendar' : {
            	eventclick : this.eventClicked
            }
        });
    },
    
    mayDelete : function(grid, rowIndex, columnIndex, mission){
		if(columnIndex==5) {
			this.getMissionsStore().remove(mission);
			this.getMissionEditor().getForm().reset();
			this.disableEditor();
		}
	},
    
    newMission: function() {
    	this.getMissionList().getSelectionModel().deselectAll();
    	if(this.editedMission) {
    		this.getMissionEditor().getForm().reset();
    	}
    	this.editMission(this.getMissionModel().create({}));
    },
    
    eventClicked : function(calendar, event, el) {
    	this.getMissionList().getSelectionModel().select(event);
    },
    
    editSelectedMission : function(selModel, selected) {
    	var mission = selected[0];
    	if(mission) {
    		this.updateForm(mission);
    		this.editMission(mission);
    	}
    },
    
    updateForm : function(mission) {
		var fields = this.getMissionEditor().getForm().getFields();
		fields.get('Date').setValue(mission.get('StartDate'));
        fields.get('StartTime').setValue(mission.get('StartDate'));
        fields.get('StartLocation').setValue(mission.get('StartLocation'));
        fields.get('EndLocation').setValue(mission.get('EndLocation'));
        fields.get('TravelTime').setValue(this.floatToTime(mission.get('TravelTime')));
        fields.get('Hardware').setValue(mission.get('Hardware'));
        fields.get('Work').setValue(mission.get('Work'));
        fields.get('WorkTime').setValue(this.floatToTime(mission.get('WorkTime')));
    },
    
    editMission: function(mission) {
    	var fields = this.getMissionEditor().getForm().getFields();
        fields.each(function(field){
        	field.enable();        		
        });
        this.getMissionEditorSave().enable();
        this.getMissionEditorCancel().enable();
        fields.get('StartLocation').focus();
    	this.editedMission = mission;    	
    },
    
    saveMission : function() {
    	var mission = this.editedMission,
    	form = this.getMissionEditor().getForm(),
    	store = this.getMissionsStore(),
    	fields = form.getFields();
    	var startDate = Ext.Date.parse(fields.get('Date').getRawValue()+' '+fields.get('StartTime').getRawValue(),'d/m/Y H:i');
    	mission.set('StartDate',startDate);
    	mission.set('StartLocation',fields.get('StartLocation').getValue());
    	mission.set('EndLocation',fields.get('EndLocation').getValue());
    	mission.set('TravelTime',this.timeToFloat(fields.get('TravelTime').getValue()));
    	mission.set('Work',fields.get('Work').getValue());
    	mission.set('WorkTime',this.timeToFloat(fields.get('WorkTime').getValue()));
    	var duration = this.timeToFloat(fields.get('TravelTime').getValue())+this.timeToFloat(fields.get('WorkTime').getValue());
    	var endDate = Ext.Date.add(startDate, Ext.Date.HOUR, Math.floor(duration));
    	endDate = Ext.Date.add(endDate, Ext.Date.MINUTE, (duration - Math.floor(duration)) * 60);
    	mission.set('EndDate',endDate);
    	//var day = Ext.Date.parse(fields.get('Date').getRawValue(),'d/m/Y');
    	var day = fields.get('Date').getValue();
    	mission.set('Day',day);
    	mission.set('Title',fields.get('EndLocation').getValue());
    	mission.set('Hardware',fields.get('Hardware').getValue());
    	switch (fields.get('Hardware').getValue()) {
	    	 case 'C':
	    		 mission.set('CalendarId',1);
	    		 break;
	    	 case 'CR':
	    		 mission.set('CalendarId',2);
	    		 break;
	    	 default:
	    		 mission.set('CalendarId',3);
	    	 	break;
    	};
    	if(!mission.store){
    		store.add(mission);
    	}
    	store.save();
    	form.reset();
    	fields.get('StartTime').setValue(endDate);
    	this.editedMission = null;
    	this.disableEditor();
    },
    
    timeToFloat : function(time) {
    	return time.getHours()+time.getMinutes()/60;
    },
    
    floatToTime : function(f) {
    	var ret = Ext.Date.add(new Date(0,0,0),Ext.Date.HOUR,Math.floor(f));
    	return Ext.Date.add(ret,Ext.Date.MINUTE,(f-Math.floor(f))*60);
    },
    
    cancelMission: function() {
    	this.getMissionList().getSelectionModel().deselectAll();
    	this.getMissionEditor().getForm().reset();
    	this.disableEditor();
    },
    
    disableEditor: function() {
    	fields = this.getMissionEditor().getForm().getFields();
        fields.each(function(field){
        	field.disable();        		
        });
        this.getMissionEditorSave().disable();
        this.getMissionEditorCancel().disable();
    }
});
